//index.js
//获取应用实例
const app = getApp()
const Pager = require('components/aotoo/core')
let mkNav = require('components/modules/navlist')


import {data} from './data'

const adapterLikeTab = (data) =>{
  let content = []
  let menus = []
  data.map((item, ii) => {
    item.id = 'ss_'+ item.id
    menus.push({
      title: item.moduleName,
      itemClass: ii === 0 ? 'active' : '',
      id: item.id,
      aim: 'onMenus?id='+item.id+'&idx='+ii
    })
    content.push({
      id: 'c_'+item.id,
      title: {
        title: item.moduleName,
        itemClass: `title-default mb-default ${ii === 0 ? 'xx' : ''}`
      },
      '@html': {
        content: item.subModule[0].freeContent,
        openTag(name, tag) {
          if (name === 'img') {
            if (tag['@image'] ['class'] !== 'small-emotion') {
              tag['@image']['lazy-load'] = true
              tag['@image']['mode'] = 'widthFix'
            }
            // else {
            //   tag['@image']['bindload'] = 'onloadImg'
            // }
          }
          return tag
        }
      },
      itemClass: 'detail-body-item item-skeleton'
      // itemStyle: `display: var(--item-${ii}, none)`
    })
  })
  return {menus, content}
}



Pager({
  data: {
    pagesClass: '',
    skeleton: 'skeleton',
    scrollTop: 0,
    navbarData: {
      height: app.globalData.navheight,
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '', //导航栏 中间的标题
      bg: 'rgb(255 255 255 / 0)',
      position: 'fixed'
      // url: '/pages/index/index'
    },
    isFixed: false,
    height: app.globalData.navheight,
    header: {
      $$id: 'header'
    },
    tabHeader: {
      $$id: 'tabHeader'
    },
    tabMenus: {
      $$id: 'tabMenus'
    },
    tabMenusInst: [],
    tabeMenusActiveIdx: 0,
    tabContentInst: [],
    tabContent: {
      $$id: 'tabContent'
    },
    // body: {
    //   $$id: 'paegsInst'
    // },
    // content: {
    //   $$id: 'content'
    // },
    footer: {
      $$id: 'paegsBtn'
    },
    clicked: false,
    isScroll: false
  },
  $paegsInst: null,
  execData: [],
  adapter(data, status) {
    const that = this
    const img = (src, type) => {
      let content = []
      let dot = []
      src.map((item, ii) => {
        content.push({
          img: {
            src: item.filePath,
            mode: 'scaleToFill',
            'lazy-load': true
          },
          itemClass: 'item-pic-wrap item-skeleton',
        })
        if (type === 'dot') {
          dot.push({
            title: ' ',
            itemClass: ii === 0 ? 'active' : ''
          })
        }
      })
      return {content, dot}
    }
    const swiperData = img(data.fitments, 'dot')
    const isBanner = {
      data: swiperData.content,
      footer: {
        '@list': {
          $$id: 'swiper-dot-cu',
          data: swiperData.dot,
          listClass: 'ss-banner-dot',
          itemClass: 'item-dot'
        }
      },
      type: {
        is: 'swiper',
        interval: 2000,
        duration: 500,
        bindchange: 'bindchange'
      },
      listClass:'ss-banner'
    }
    const contentData = adapterLikeTab(data.subStrategy)
    return {
      header: isBanner,
      tabHeader: {
        title: [
          { title: data.productName, itemClass: 'size-title-lg fw-bold color-title item-skeleton' },
          { title: [{title: data.publishDateTime, itemClass: 'color-title'}, {title: data.positionName, itemClass: 'color-default'}], titleClass: 'size-form flex-row-between mtb-default item-skeleton'}
        ],
        titleClass: 'p-default item-head',
      },
      tabMenus: {
        data: contentData.menus,
        itemClass: 'item-title item-menus item-skeleton',
        listClass: 'list-tabs xxx-body',
        type: {
          is: 'scroll',
          'scroll-x': true,
          'enable-flex': true,
        },
        listStyle: '--tabidx: 0'
      },
      tabContent: {
        data: contentData.content,
        listClass: 'demo-body p-default',
        itemClass: 'detail-body-item item-skeleton',
        type: {
          is: "swiper",
          vertical: true,
        }
      },
      footer: mkNav({
        data: [{title: '收藏', itemClass: 'item-skeleton nav-item icon-collect', aim: 'onFixedBtn?type=collect'}, {title: '点赞', itemClass: 'item-skeleton nav-item icon-like', aim: 'onFixedBtn?type=like'}, {itemClass: 'item-skeleton nav-item icon-share', '@button': {id: 'case-share', type: 'button', value: '分享', 'open-type': 'share', itemClass: 'ss-btn-text'}}],
        // listClass: 'skeleton'
      })
    }
  },
  // clicked: false,
  preItemInstId: 'ss_2',
  onMenus(e) {
    const _id = e.currentTarget.id
    const _idx = e.currentTarget.dataset.idx
    const that = this
    this.setData({
      tabeMenusActiveIdx: _idx,
      scrollTop: this.execData[_idx],
      clicked: true
    })
  },
  onloadImg(e, p, inst) {
    let $width = e.detail.width,    //获取图片真实宽度
        $height = e.detail.height,
        ratio = $width / $height;    //图片的真实宽高比例
    let screenWidth = app.globalData.screenWidth          //设置图片显示宽度，左右留有16rpx边距
    let viewHeight = ''
    let viewWidth = ''
    if ($width > screenWidth) {
      viewHeight = screenWidth / ratio;    //计算的高度值
    }
    else {
      viewHeight = $height
      viewWidth = $width
    }
    // inst.update({'@image.itemStyle': `height: ${viewHeight}px; width: ${$width > screenWidth ? '100%' : viewWidth+'px'};`})
  },
  onFixedBtn(e, p, inst) {
    const _type = p.type
    inst.addClass('active')
  },
  bindchange(e) {
    let _current = e.detail.current
    const $swiperDot = this.getElementsById('swiper-dot-cu')
    const _newDot = $swiperDot.getData().data
    _newDot.map((item, ii) => {
      item.itemClass = ''
      if (ii === _current) {
        item.itemClass +=' active'
      }
      return item
    })
    $swiperDot.update(_newDot)
  },
  onShow: function () {},
  onReady: function () {
    const that = this
    const $header = this.getElementsById('header')
    const $tabHeader = this.getElementsById('tabHeader')
    const $tabMenus = this.getElementsById('tabMenus')
    const $tabContent = this.getElementsById('tabContent')
    const $paegsBtn = this.getElementsById('paegsBtn')
    // this.$paegsInst = this.getElementsById('paegsInst')
    // this._list = this.getElementsById('content')
    $header.update(this._data.header)
    $tabHeader.update(this._data.tabHeader)
    // $tabMenus.update(this._data.tabMenus, () => {
    //   that.query3()
    //   that.getMenusQuery()
    // })
    this.setData({
      tabMenusInst: this._data.tabMenus,
      tabContentInst: this._data.tabContent,
    }, () => {
      setTimeout(() => {
        that.getScrollQuery()
      }, 0);
    })
    // $tabContent.update(this._data.tabContent, () => {
    //   that.setData({
    //     skeleton: ''
    //   }, () => {
    //     that.query3()
    //     that.getScrollQuery()
    //   })
    // })
    // this.$paegsInst.update(this._data.body)
    // this.$paegsInst.update(this._data.body, function() {
    //   that.query3()
    //   that.getScrollQuery()
    //   that.getMenusQuery()
    //   that.setData({
    //     skeleton: ''
    //   })
    // })
    $paegsBtn.update(this._data.footer)
  },
  getMenusQuery() {
    const xx = wx.createSelectorQuery().in(this)
    const that = this
    setTimeout(() => {
      xx.selectAll('.boxer>>>.item-menus').boundingClientRect().exec(ret=>{
        if (ret[0] === null) return;
        that.itemMonitorMenus = ret[0]
      })
    }, 10);
  },
  getScrollQuery() {
    const that = this
    const scrollQuery = wx.createSelectorQuery().in(this)
    setTimeout(() => {
      scrollQuery.select('.boxer>>>.page-tab-menus').boundingClientRect(ret=>{
        console.log('ret', ret)
        that.kkk = ret.top - 60
      }).exec()
      scrollQuery.selectAll('.boxer>>>.ss-block').boundingClientRect(ret=>{
        ret.forEach((item, ii) => {
          console.log(item, '=================2222', ii)
          item.top = ii === 0 ? item.top - 110 : item.top - 54
          // console.log(item.top, '=================3333')
          that.execData.push(item.top)
        })
      }).exec()
      that.setData({
        skeleton: '',
        isScroll: true
      })
    }, 500);
  },
  scrollUpdateMenus(idx) {
    this.getMenusQuery()
    const _ndata = this.$menusInst.getData().data
    let _id = ''
    _ndata.map((item, ii) => {
      item.itemClass = ''
      if (ii == idx || item.id === idx) {
        idx = ii
        item.itemClass +=' active'
      }
      return item
    })
    if (this.itemMonitorMenus && ((this.itemMonitorMenus[idx].left + this.itemMonitorMenus[idx].width) >= app.globalData.screenWidth || this.itemMonitorMenus[idx].left < 0)) {
      _id = this.itemMonitorMenus[idx].id
    }
    let scrollCfg = {}
    if (idx !== 0) {
      scrollCfg = {'type.scroll-into-view': _id}
    }
    else {
      scrollCfg = {'type.scroll-left': 0}
    }
    this.$menusInst.update({data: _ndata, ...scrollCfg})
    // this.$menusInst.update({data: _ndata, listClass: 'list-tabs box-shadow-bottom', ...scrollCfg})
  },
  isNavBg: true,
  curMenusIdx: 0,
  scrollChangeMenus(top) {
    this.execData.forEach((item, index) => {
      if ( top >= item && top < this.execData[index + 1]) {
        if (this.data.tabeMenusActiveIdx === index) return 
        this.setData({
          tabeMenusActiveIdx: index,
        })
      }
      if (top >= this.execData[this.data.tabeMenusActiveIdx + 1]) {
          if (this.data.tabeMenusActiveIdx + 1 === this.execData.length) return
          this.setData({
            tabeMenusActiveIdx: this.execData.length - 1,
          })
      }
    })
  },
  binddragend(e) {
    const that = this
    setTimeout(() => {
      that.setData({
        clicked: false
      })
    }, 500);
  },
  bindscroll(e) {
    const top = e.detail.scrollTop
    console.log(top, 'top')
    const that = this
    if (!this.data.clicked) {
      this.scrollChangeMenus(top)
    }
    if (top >= this.kkk) {
      if (!this.isNavBg) return
      this.setData({
        'navbarData.bg': `rgb(255 255 255 / 100%)`,
        'navbarData.title': '详情页',
        isFixed: true
      }, () => {
        that.isNavBg = false
      })
    }
    if (top < this.kkk) {
      if (this.isNavBg) return 
      this.setData({
        'navbarData.bg': `rgb(255 255 255 / 0)`,
        'navbarData.title': '',
        isFixed: false
      })
      this.isNavBg = true
    }
  },
  hasIdx: [0],      //为了不重复执行
  preScrollTop: null,
  onLoad: function (options) {
    // if (options.from) {
    //   this.data = this.adapter(_normal)
    // }
    // else {
      this._data = this.adapter(data.data, true)
    // }
  }
})
